package ua.openmedis.dao.impl;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.Tuple;
import javax.persistence.TypedQuery;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import ua.openmedis.ServerUtils;
import ua.openmedis.dao.api.AssetDAO;
import ua.openmedis.domain.AssetGenericName_;
import ua.openmedis.domain.Assets;
import ua.openmedis.domain.Assets_;
import ua.openmedis.domain.Contact_;
import ua.openmedis.domain.Location_;
import ua.openmedis.domain.Manufactures_;
import ua.openmedis.service.dto.Asset;

public class AssetDAOImpl implements AssetDAO{
	
	private static final Logger log = LoggerFactory.getLogger(AssetDAO.class);

	EntityManager em = ServerUtils.getEntityManager();
	
	@Override
	public List<Asset> findAssets(int count) {
		log.debug("Searching ASSETS...");
		CriteriaBuilder cb = em.getCriteriaBuilder();
		CriteriaQuery<Tuple> q = cb.createTupleQuery();
		Root<Assets> asset = q.from(Assets.class);
		
		// Aliases
		final String ASSET_ID = "assetId";
		final String UMDNS_CODE = "umdnsCode";
		final String GENERIC_NAME = "genericName";
		final String ASSET_FULL_NAME = "assetFullName";
		final String MANUFACTURER = "manufacturer";
		final String MODIFIED_BY = "modifiedBy";
		final String LOCATION_BUILDING = "locationBuilding";
		
		q.multiselect(asset.get(Assets_.assetId).alias(ASSET_ID),
						asset.get(Assets_.assetgenericname).get(AssetGenericName_.genericAssetCode).alias(UMDNS_CODE),
						asset.get(Assets_.assetgenericname).get(AssetGenericName_.genericAssetName).alias(GENERIC_NAME),
						asset.get(Assets_.assetFullName).alias(ASSET_FULL_NAME),
						asset.get(Assets_.manufactures).get(Manufactures_.contact).get(Contact_.contactName).alias(MANUFACTURER),
						asset.get(Assets_.byUser).alias(MODIFIED_BY),
						asset.get(Assets_.location).get(Location_.building).alias(LOCATION_BUILDING));
		
		TypedQuery<Tuple> tupedQuery = em.createQuery(q).setMaxResults(count);
		List<Tuple> resultTuple = tupedQuery.getResultList();
		
		List<Asset> result = new ArrayList<Asset>();
		Asset temp;
		for(Tuple item : resultTuple){
			temp = new Asset();
			temp.setAssetId((String)item.get(ASSET_ID));
			temp.setUmdnsCode((String)item.get(UMDNS_CODE));
			temp.setGenericName((String)item.get(GENERIC_NAME));
			temp.setFullName((String)item.get(ASSET_FULL_NAME));
			temp.setManufacturer((String)item.get(MANUFACTURER));
			temp.setModifiedBy((String)item.get(MODIFIED_BY));
			temp.setLocationBuilding((String)item.get(LOCATION_BUILDING));
			result.add(temp);
		}
		
		log.debug("Assets were found:" + result.toString());
		return result;
	}

}
